package com.project.server.controller;

import com.project.server.common.api.Result;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.UUID;

@RestController
@RequestMapping("/api/file")
public class FileController {

    @Value("${upload.path}")
    private String uploadPath;

    @Value("${upload.url-prefix}")
    private String urlPrefix;

    @PostMapping("/upload")
    public Result<String> upload(MultipartFile file) {
        try {
            // 生成新的文件名
            String originalFilename = file.getOriginalFilename();
            String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
            String newFileName = UUID.randomUUID().toString() + suffix;

            // 确保目录存在
            File uploadDir = new File(uploadPath);
            if (!uploadDir.exists()) {
                uploadDir.mkdirs();
            }

            // 保存文件
            File destFile = new File(uploadPath + File.separator + newFileName);
            file.transferTo(destFile);

            // 返回文件访问URL
            return Result.success(urlPrefix + newFileName);
        } catch (Exception e) {
            return Result.error("文件上传失败：" + e.getMessage());
        }
    }

    @GetMapping("/uploads/**")
    public void getImage(HttpServletRequest request, HttpServletResponse response) {
        try {
            // 获取图片路径
            String uri = request.getRequestURI();
            String imagePath = uri.substring("/api/file/uploads/".length());

            // 构建完整的文件路径
            File file = new File(uploadPath + File.separator + imagePath);
            if (!file.exists()) {
                response.sendError(HttpServletResponse.SC_NOT_FOUND);
                return;
            }

            // 设置响应头
            String contentType = request.getServletContext().getMimeType(file.getName());
            response.setContentType(contentType);
            response.setHeader("Cache-Control", "max-age=31536000");

            // 写入响应
            Files.copy(file.toPath(), response.getOutputStream());
            response.getOutputStream().flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }














}
